package com.example.getfromservice.Activity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import com.example.getfromservice.R;
import com.example.getfromservice.Book.Book;
import com.example.getfromservice.Book.BookDAO;
import com.example.getfromservice.Book.DataHandlerBook;
import com.example.getfromservice.Category.Category;
import com.example.getfromservice.Category.CategoryDAO;
import com.example.getfromservice.Category.DataHandler;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends Activity {

	private LongRunningGetIO mLongRunningIO = null;
	private LongRunningBackup mLongRunningBackup = null;
	private LongRunningSync mLongRunningSync = null;
	private LongRunningDelete mLongRunningDelete = null;
	private ListView myListView;
	private ArrayAdapter<Category> adapter;
	private List<Category> values = new ArrayList<Category>();	
	private boolean mDone = true;
	private CategoryDAO datasource; 
	private BookDAO bookdatasource;
	private Category category;
	private int ID_Object = -1;
	private Intent myintent;
	private Map<Integer,List<Book>> map_books;
	private HttpClient httpclient;
	private HttpDelete httpdelete;
	private HttpResponse response;
	private DataHandler xmlparser;
	private DataHandlerBook xmlpareserbook;
	private HttpPut httpput;
	private HttpPost httppost;

	
//*********************************************** ONCREATE *****************************************

	@Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        map_books = new HashMap<Integer, List<Book>>();
           
        datasource = new CategoryDAO(this);
        bookdatasource = new BookDAO(this);
        httpclient =  new DefaultHttpClient();


	    myListView = (ListView)findViewById(android.R.id.list);

	 	   
	 	   myListView.setOnItemClickListener(new OnItemClickListener() {
           public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {

           	   ID_Object = myItemInt;
        	   
           	   final CharSequence[] items = {"Edit", "Delete", "Show books"};

        	   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        	   builder.setTitle("Pick an action : ");
        	   builder.setItems(items, new DialogInterface.OnClickListener() {
        	       public void onClick(DialogInterface dialog, int item) {
        	          
        	    	   	category = new Category();
						category = values.get(ID_Object);
						
        	    	    switch(item)
        	    	    {
        	    	    	case 0:
        	    	    			{
        	    	    					myintent = new  Intent(getApplicationContext(), SecondActivity.class);
        	    	    			        	    	    					
        						        	// Info - { category_id , action }
        						        	// category_id - if new then 0 
        						        	// action  0 - new ; 1 - update
        									myintent.putExtra( "Info", new int[]{category.getID(),1} );
        									startActivity(myintent);
        	    	    			}
                	    	    
        	    	    	break;
        	    	    	
        	    	    	case 1:
        	    	    			{
        	    	    					
        	    	    					
        	    	    					values.remove(category);
        	    	    					
        	    	    					boolean needToCreate = false;
        	    	    		  			if (mLongRunningDelete == null) {
        	    	    		  			      needToCreate=true;
        	    	    		  			} else {
        	    	    		  				if (mLongRunningDelete.isDone()) {
        	    	    		  					needToCreate=true;
        	    	    		
        	    	    		  					mLongRunningDelete = null;
        	    	    		  				}
        	    	    		  			}
        	    	    		  			if (needToCreate) {
        	    	    		  				mLongRunningDelete = new LongRunningDelete();
        	    	    		  				mLongRunningDelete.execute(category.getID()+"");
        	    	    		  			}
        	    	    		  			
        	    	    		  			
        	    	    			}
                	    	    
        	    	    	break;
        	    	    	
        	    	    	case 2:
	        	    	    		{
	        	    	    			
	            	    	    		myintent = new Intent(getApplicationContext(),ThirdActivity.class);
	            	    	    			            	    	    	
	            	    	    		myintent.putExtra("CategoryID", category.getID() );
	            	    	    		startActivity(myintent);
	        	    	    		}
            	    	    		
        	    	    	break;
        	    	    	
        	    	    		
        	    	    }
        	       }
        	   });
        	   
        	   AlertDialog alert = builder.create();
		 	   alert.show();
        	   
             }                 
       });
 	   
    }
    
//*********************************************** MENU *********************************************

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
 
        switch (item.getItemId())
        {
	        case R.id.menu_new: 
						        {
						        	myintent = new  Intent(getApplicationContext(), SecondActivity.class);
									int last_id;
						        	// Info - { last_category_id , action }
						        	// category_id - if new then 0 
						        	// action  0 - new ; 1 - update
						        
									if(values.size() > 0)
						        		{
						        			Category cat = values.get(values.size()-1);
						        			last_id = cat.getID();
						        		}
						        	else
							        	{
							        		last_id = 0;
							        	}
									myintent.putExtra( "Info", new int[]{last_id,0} );
									startActivity(myintent);
						        }
	        return true;
	 
	        case R.id.menu_backup:
							        {
							        	boolean needToCreate = false;
						    			
						     			if (mLongRunningBackup == null) {
						     			      needToCreate=true;
						     			} else {
						     				if (mLongRunningBackup.isDone()) {
						     					needToCreate=true;
						
						     					mLongRunningBackup = null;
						     				}
						     			}
						     			if (needToCreate) {
						     				mLongRunningBackup = new LongRunningBackup();
						     				mLongRunningBackup.execute();
						     			}
							        }
	            
	        	return true;
	 
	        case R.id.menu_sync:
						        {
						        	boolean needToCreate = false;
						  			if (mLongRunningSync == null) {
						  			      needToCreate=true;
						  			} else {
						  				if (mLongRunningSync.isDone()) {
						  					needToCreate=true;
						
						  					mLongRunningSync = null;
						  				}
						  			}
						  			if (needToCreate) {
						  				mLongRunningSync = new LongRunningSync();
						  				mLongRunningSync.execute();
						  			}
						        }
	            return true;
	 
	        
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }    
   
//*********************************************** ISONLINE ****************************************       
    
    public boolean isOnline() {
    	
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
       
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
           
        	return true;
        }
        
        return false;
    }
  
//*********************************************** ONRESUME ****************************************
    
    @Override
    protected void onResume() {
      
    	datasource.open();
    	bookdatasource.open();
    	super.onResume();
     	   
     
      boolean needToCreate = false;
		if (mLongRunningIO == null) {
		      needToCreate=true;
		} else {
			if (mLongRunningIO.isDone()) {
				needToCreate=true;

				mLongRunningIO = null;
			}
		}
		if (needToCreate) {
			mLongRunningIO = new LongRunningGetIO();
			mLongRunningIO.execute();
		}
      
    }

//*********************************************** ONPAUSE *****************************************
   
    @Override
    protected void onPause() {
      
    	datasource.close();
    	bookdatasource.close();
    	super.onPause();
    	
    }
    
//*********************************************** GETDATA *****************************************
    
    private class LongRunningGetIO extends AsyncTask<Void, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Void... params) {

			try
	        {
								
					if( isOnline())
				      	{
				    	  
							  	xmlparser = new DataHandler(MainActivity.this);
							  	values = xmlparser.getData(); 
						  
				      	}
					else if( !isOnline() )
				      	{
								values = datasource.getAllCategory();
				      	}
	              
	        }
	        catch(Exception pce) 
	        	{ 
	        		Log.e("LongRunningGetIO", "PCE "+pce.getMessage()); 
	        	}
			
			return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {

			
				  adapter = new ArrayAdapter<Category>(MainActivity.this,android.R.layout.simple_list_item_1, values);
			      myListView = (ListView)findViewById(android.R.id.list);
			  	  myListView.setAdapter(adapter);
				
			  	   
			}
	
		}

	}
    
//*********************************************** DELETE ******************************************
    
    private class LongRunningDelete extends AsyncTask<String, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(String... params) {
		
				if( !isOnline() )
					{
						category = new Category();
						
						category = datasource.selectCategoryfromDB(Integer.parseInt(params[0]));
						
						category.setChanges(3);
						datasource.updateCategoryinDB(category);
					}
				else if( isOnline() )
					{
						try{
			
				    	 
				    	     httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+params[0]);
				    	    
				    	     response = httpclient.execute(httpdelete);  
			
				    	     Log.i("Respones",response.toString());
				    	    	
				        }catch(Exception pce) 
				        	{ 
				        		Log.e("LongRunningDelete", "PCE "+pce.getMessage()); 
				        	
				        	}
					}
			
			return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {
				
				adapter.notifyDataSetChanged(); 
							     		
			}
	
		}

	}
    
//*********************************************** BACKUP ******************************************  
    
    private class LongRunningBackup extends AsyncTask<Void, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Void... params) {

			try{
	               
					datasource.deleteAllCategory();
					bookdatasource.deleteAllBooks();
					
					
					for( int i = 0 ; i < values.size() ; i++)
	    				{
	    				
		    				category = new Category();
		    				category = values.get(i);
		    				category.setChanges(0);		    				
		
		    				datasource.createCategory(category);
	
	    				}
					
				    xmlpareserbook = new DataHandlerBook();
			    	List<Book> tmpbooks = new ArrayList<Book>();
			    	
			    	  
			    	  for( Category cat : values)
			    	  	{
			    		  
			    		  	tmpbooks = xmlpareserbook.getAllBooks(cat.getID()+"");
			    	
			    		  	map_books.put(cat.getID(), tmpbooks);

			    	  	}
			    	 
			    	  
					for (Map.Entry<Integer, List<Book>> entry : map_books.entrySet())
						{
							   
							  List<Book> cs = map_books.get(entry.getKey());
							   
							   if( cs.size() > 0 && cs != null)
								   {
								   		bookdatasource.addBooks(cs,entry.getKey());
								   }
							   
					   
								
						}

					
				
	        }catch(Exception pce) { 
	        	
	        	Log.e("LongRunningBackup", "PCE "+pce.getMessage()); 
	        	
	        }
		
			return 1;	
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {
 
				Toast.makeText(getApplicationContext(), "Backup completed !" , Toast.LENGTH_SHORT).show();
			  	   				
			}
	
		}

	}
      
//*********************************************** SYNC ********************************************
    
    private class LongRunningSync extends AsyncTask<Void, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Void... params) {
		
				try{	

		    	     	httpput = new HttpPut("http://10.0.2.2:8020/categoryservice/category/");

		    	    	List<Category> listtosync = datasource.getAllCategorytoSync();
		    	   
		    	    	
		    	    	
		    	    	for (Category cat : listtosync) {
		    	    		
			    	    		String xml = "<Category><categoryId>"+cat.getID()+"</categoryId><categoryName>"+cat.getName()+"</categoryName></Category>";
			    	    		StringEntity se = new StringEntity(xml,HTTP.UTF_8);
			        	    	httpput.addHeader("Content-Type", "application/xml");
			        	    	
			        	    	//  1 - update; 2 - new ;  3- delete
			        	    	switch( cat.getChanges() )
				        	    	{
					        	    		case 1:
							        	    		{
														
										    	    	httpput.setEntity(se);  
							
										    	        response = httpclient.execute(httpput);
										    	        Log.i("Respones",response.toString());
										    	        
							        	    		}
					        	    		break;
					        	    		
					        	    		case 2:
							        	    		{
									
										    		    httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/");
											    	   
											    	    
											    	    httppost.addHeader("Content-Type", "application/xml");
											    	    
											    	  
											    	    httppost.setEntity(se);  
											    	    
											    	    se.setContentType("application/xml");
											    	    
											    	   
											    	    response = httpclient.execute(httppost);
											    	    Log.i("Respones",response.toString());
										    	        
										    	     
									    	    	}
						        	    	break;
						        	    		
					        	    		case 3:
							        	    		{
							        	    			httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+cat.getID());
							        	 	    	    response = httpclient.execute(httpdelete);  
						
							        	 	    	    Log.i("Respones",response.toString());
							        	 	    	   
							        	    		}
						        	    	break;
				        	    	}

		    	    	}
		    	    	
		    	    	
		    	    	List<Category> deletelist = datasource.getAllCategoryParam(3);
		    	    	
		    	    	for (Category cat : deletelist) {
		    	    		
		    	    		datasource.deleteCategory(cat);
		    	    	}
		    	    	
		    	    	List<Category> updatelist = datasource.getAllCategory();
		    	    	
		    	    	for (Category cat : updatelist) {
		    	    		
		    	    		cat.setChanges(0);
		    	    		datasource.updateCategoryinDB(cat);
		    	    	}
		    	    	
		    	    	List<Book> bookToSync = bookdatasource.getAllBooksSync();
		    	    	
		    	    	for( Book b : bookToSync)
		    	    	{
		    	    		Bitmap tmp = b.getImage();
    						
		    	    		ByteArrayOutputStream stream = new ByteArrayOutputStream();
    						tmp.compress(Bitmap.CompressFormat.JPEG, 85, stream);
    						byte[] by = stream.toByteArray();
    						String encodedImage = Base64.encodeToString(by, Base64.DEFAULT);
    						
		    	    		String xml = "<Book><author>"+b.getAuthor()+"</author><bookISBNnumber>"+b.getISBN()+"</bookISBNnumber><bookId>"+b.getID()+"</bookId><bookName>"+b.getTitle()+"</bookName><image>"+encodedImage+"</image></Book>";
		    	    		
			    	    		switch(b.getChanges())
			    	    		{
					    	    		case 1:
							    	    		{
							    	    			
							    				
							    	    				httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+b.getCategory_id()+"/"+b.getID());
							    						
							    	    				response = httpclient.execute(httpdelete);  
							    						Log.i("Respones",response.toString());
							    													    									   
							    						httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/"+b.getCategory_id()+"/book/");
							    													    							    	 
							    						httppost.addHeader("Content-Type", "application/xml");
							    								    	    
							    						StringEntity se = new StringEntity(xml,HTTP.UTF_8);
							    						httppost.setEntity(se);  
							    								    	    
							    						se.setContentType("application/xml");
							    								    	    
							    						// Execute HTTP Post Request
							    						response = httpclient.execute(httppost);
							    						Log.i("Respones",response.toString());
							    						
							    						b.setChanges(0);
							    						bookdatasource.updateBookinDB(b);
							    						    	   
							    	    		}
					    	    		break;
					    	    		
					    	    		case 2:
					    	    				{
					    	    															
					    	    						httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/"+b.getCategory_id()+"/book/");
					    	    																    	    
					    	    						httppost.addHeader("Content-Type", "application/xml");
										    	    
					    	    						StringEntity se = new StringEntity(xml,HTTP.UTF_8);
					    	    						httppost.setEntity(se);  
										    	    
					    	    						se.setContentType("application/xml");
										    	    
					    	    						// Execute HTTP Post Request
					    	    						response = httpclient.execute(httppost);
					    	    						Log.i("Respones",response.toString());
					    	    				}
					    	    		break;
					    	    		
					    	    		case 3:
					    	    				{
					    	    					
					    	    					  	httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+b.getCategory_id()+"/"+b.getID());
			    							    	    
			    							    	    response = httpclient.execute(httpdelete);  
			    							    	    Log.i("Respones",response.toString());
			    							    	    
			    							    	    bookdatasource.deleteBook(b);
					    	    				}
					    	    		break;
			    	    		}
		    	    		
		    	
		    	    	
		    	    	}
	
		        }catch(Exception pce) { 
		        	
		        	Log.e("LongRunningSync", "PCE "+pce.getMessage()); 
		        }
			return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {
					
				Toast.makeText(getApplicationContext(), "Sync completed !" , Toast.LENGTH_SHORT).show();
			}
	
		}

	}
    
    
    
   
    
    
}
